﻿using IOP.SgrA;
using IOP.SgrA.SilkNet.Vulkan;
using Silk.NET.Vulkan;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;

namespace VkSample104
{
    public class ItemMiddleware : IProductionLineMiddleware<VulkanContext>
    {
        public void Invoke(VulkanContext context, RenderingProductionLineDelegate<VulkanContext> next)
        {
            var render = context.GetContextRenderObject();
            var pipeline = context.VulkanPipeline;
            int size = Marshal.SizeOf<Matrix4x4>() * 2;
            ref MVPMatrix local = ref context.GetMVPMatrix();
            Matrix4x4 mat = local.GetFinalMatrix() * context.ClipMatrix;
            byte[] data = ArrayPool<byte>.Shared.Rent(size);
            Span<byte> span = data;
            span = span.Slice(0, size);
            mat.ToBytes(ref span, 0);
            local.ModelMatrix.ToBytes(ref span, 64);

            var vro = render.GetComponents<VRO>().First();
            var cmd = context.CommandBuffer;

            var sets = pipeline.GetPipelineDescriptorSet(0);
            cmd.BindDescriptorSets(PipelineBindPoint.Graphics, pipeline.PipelineLayout, 0, null, sets);
            cmd.BindVertexBuffers(0, stackalloc ulong[] { 0 }, vro.VerticesBufferInfo.Buffer);
            cmd.PushConstants(pipeline.PipelineLayout, ShaderStageFlags.ShaderStageVertexBit, 0, span.ToArray());
            cmd.Draw(vro.VecticesCount, 1, 0, 0);
            ArrayPool<byte>.Shared.Return(data);
        }
    }
}
